package com.drug.mingkang.security.interceptor;

import com.alibaba.fastjson.JSON;
import com.drug.mingkang.utils.ResponseMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 描述：用于拦截未登录请求
 *
 * @version 1.0
 * @author: wcj
 * @Date: 2020/8/3 15:05
 */
@Component
@Slf4j
public class SessionInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        String path = request.getServletPath();
        System.out.println("path = " + path);

        //无论访问的地址是不是正确的，都进行登录验证，登录成功后的访问再进行分发，404的访问自然会进入到错误控制器中
        HttpSession session = request.getSession();
        if (!StringUtils.isEmpty(session.getAttribute("loginUserId")))
        {
            try
            {
                //验证当前请求的session是否是已登录的session
                String loginSessionId = stringRedisTemplate.opsForValue().get("loginUser" + String.valueOf(session.getAttribute("loginUserId")));
                log.error(loginSessionId);
                if (loginSessionId != null && loginSessionId.equals(session.getId()))
                {
                    return true;
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return true;
        }

        response401(response);
        return false;
    }

    private void response401(HttpServletResponse response)
    {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try
        {
            response.getWriter().print(JSON.toJSONString(ResponseMessage.error("用户未登录")));
            response.sendRedirect("/ok-admin/pages/login.html");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

}
